package com.small.nacos.naming.web;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.small.nacos.core.code.ControllerMethodsCache;
import com.small.nacos.naming.core.DistroMapper;
import com.small.nacos.naming.core.utils.WebUtils;
import com.small.nacos.naming.misc.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

/**
 * @Author zhoujin
 * @Date 2022/10/31 11:18
 */
public class DistroFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(DistroFilter.class);

    @Autowired
    private DistroMapper distroMapper;

    @Autowired
    private ControllerMethodsCache controllerMethodsCache;

    private static final int PROXY_CONNECT_TIMEOUT = 2000;

    private static final int PROXY_READ_TIMEOUT = 2000;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String serviceName = req.getParameter(CommonParams.SERVICE_NAME);
        String groupName = req.getParameter(CommonParams.GROUP_NAME);
        if (StringUtils.isBlank(groupName)) {
            groupName = Constants.DEFAULT_GROUP;
        }
        String groupedServiceName = serviceName;
        if (StringUtils.isNotBlank(serviceName) && !serviceName.contains(Constants.SERVICE_INFO_SPLITER)) {
            groupedServiceName = groupName + Constants.SERVICE_INFO_SPLITER + serviceName;
        }
        String urlString = req.getRequestURI();
        try {
            //1.根据uri获取method
            Method method = controllerMethodsCache.getMethod(req);

            if (method == null) {
                throw new NoSuchMethodException(req.getMethod() + " " + urlString);
            }
            //2.判断当前方法是否有目标注解并且是否负责此次请求
            if (method.isAnnotationPresent(CanDistro.class) && !distroMapper.responsible(groupedServiceName)) {
                //3.获取处理
                final String targetServer = distroMapper.mapSrv(groupedServiceName);
                RestResult<String> result = HttpClient
                        .request("http://" + targetServer + req.getRequestURI(), req,
                                PROXY_CONNECT_TIMEOUT, PROXY_READ_TIMEOUT, StandardCharsets.UTF_8.name());
                String data = result.ok() ? result.getData() : result.getMessage();
                try {
                    WebUtils.response(resp, data, result.getCode());
                } catch (Exception ignore) {
                    LOGGER.warn("[DISTRO-FILTER] request failed: " + urlString);
                }
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Server failed," + ExceptionUtil.getAllExceptionMsg(e));
        }


    }
}
